package Server.List;

import bean.novelBean;
import bean.userBean;
import dao.Db;
import util.JSON;
import util.novelReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

public class novelShowServer {
    private HttpServletRequest request;
    private HttpSession session;

    private HttpServletResponse response;
    private String novelName;           //在看的书名
    private String novelNumber;
    private userBean user;
    private String realPath;
    private HashMap<String , Integer> bookSelf;     //  书架
    public novelShowServer(HttpServletRequest request, HttpServletResponse response , String realPath) throws IOException, SQLException {
        this.request = request;
        this.response = response;
        this.realPath=realPath;
        this.request.setCharacterEncoding("UTF-8");
        this.response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();
        this.novelName=getDB_novelName();           //获取书名
        if(novelName==null || novelName.trim().equals(""))
            throw  new IOException("novel is null!");
        this.bookSelf= (HashMap<String, Integer>) session.getAttribute("bookSelf");            //获取书架
        if(bookSelf==null)
            bookSelf=new HashMap<>();
        this.user = (userBean)session.getAttribute("user");         //获取用户
        System.out.println(novelName);
        session.setAttribute("novelNameCurrent",novelName);
    }
    //通过地址栏的小说编号 查询 书名
    private String getDB_novelName() throws IOException, SQLException {
        Db db=new Db();
        String sql = "select * from tb_novel where novelNumber=?";
         novelNumber = request.getParameter("novelNumber");
        ResultSet rs = db.select(sql,novelNumber);   //从地址栏中获取要看的小说编号
        session.setAttribute("novelNumberCurrent",novelNumber);
        if(rs==null)
            throw new IOException("db error");
        if (rs.next() == false)	{						//尝试读取下一条记录，如果未读到记录
            db.close();
            throw new IOException("select is null");
        }

        return rs.getString("novelName");
    }
    //下一页
    public void nextPage() throws IOException {
        int chapter = getChapter();
        //调用阅读器
        //如果阅读器报错 就是到最后一章了
        readAssignedArticle(chapter+1);
    }
    //上一页
    public void previousPage() throws IOException {
        int chapter = getChapter();
        //调用阅读器
        //如果阅读器报错 就是到最前一章了
        readAssignedArticle(chapter-1);

    }
    //指定页面
    public void assignedPage() throws Exception {
        //获取最后章节
        int lastChapter = getLastChapter();

        int searchChapter = Integer.parseInt(request.getParameter("searchChapter"));
        if(1<=searchChapter && searchChapter<=lastChapter){
            readAssignedArticle(searchChapter);
        }else
            throw  new Exception("searchChapter is error!");

    }
    private void readAssignedArticle(int chapter) throws IOException {
        try{
            String targetFilePath = String.format("%s/novelTXT/%s/%d.txt",realPath,novelName,chapter);
            String content = novelReader.readContent(targetFilePath);

            bookSelf.put(novelName,chapter);
            session.setAttribute("bookSelf",bookSelf);
            session.setAttribute("content",content);
            updateBookSelfBySQL();
        }catch (Exception e){
            throw new IOException("don't reader page");
        }
    }
    //获取最后章节
    private  int getLastChapter(){

        int l=1,r=20000,mid;
        while(l<=r){
            mid=l+((r-l)>>1);
            String targetFilePath = String.format("%s/novelTXT/%s/%d.txt",realPath,novelName,mid);
            File file = new File(targetFilePath);
            if(file.exists()){
                l=mid+1;
            }else{
                r=mid-1;
            }
        }
        return r;
    }
    //通过书架获取章节名
    private int getChapter(){
        return bookSelf.getOrDefault(novelName,0);
    }
    //入数据库
    private void  updateBookSelfBySQL() throws Exception {
        if(user==null)
            return;
        Db db = new Db();
        String sql="update tb_user set userBookSelf=? where userNumber=?";
        String bookSelfJson= JSON.HashMapToJson(bookSelf);
        String userNumber=user.getUserNumber();
        if(db.update(sql,bookSelfJson,userNumber)==0){
            throw new Exception("更新书架数据库失败！");
        }
        db.close();
    }
    //制作阅读器的导航
   public String getReaderPilot(){
        int lastChapter=getLastChapter();
        StringBuilder page=new StringBuilder(150);

        int novelCurrentChapter = bookSelf.getOrDefault(novelName,1);   //现在的页数

        String searchChapter = request.getParameter("pageShow");           //搜索的页数

        if (novelCurrentChapter <= 1) {
            page.append( "<span style='color:gray;'>首页&ensp;");
            page.append( "上一页&ensp;</span>");
        } else {
            page.append("<a href='novelShowServlet?novelNumber=" + novelNumber + "&searchChapter=1'>首页</a>&ensp;");
            page.append("<a href='novelShowServlet?novelNumber=" + novelNumber + "&searchChapter=" + (novelCurrentChapter-1) + "'>上一页</a>&ensp;");
        }

        if (novelCurrentChapter >= lastChapter) {
            page.append( "<span style='color:gray;'>下一页&ensp;");
            page.append( "尾页&ensp;</span>");
        } else {
            page.append("<a href='novelShowServlet?novelNumber=" + novelNumber + "&searchChapter=" + (novelCurrentChapter+1) + "'>下一页</a>&ensp;");
            page.append("<a href='novelShowServlet?novelNumber=" + novelNumber + "&searchChapter=" + lastChapter + "'>尾页</a>&ensp;");
        }

        page .append("&emsp;&emsp;") ;
        page .append("页码：" + novelCurrentChapter + "/" + lastChapter + "&emsp;") ;

        page .append("输入页码:") ;
        page .append("	<input type='text' id='pageShow' value='" + novelCurrentChapter + "' style='width:40px; text-align:center;'>") ;

        page .append("<input type=\"button\" onclick='submit1()' value='提交'/>") ;
        return page.toString();
    }

}
